package main

import (
	"fmt"
	"sync"
)

func main() {
	var idNames map[int]string         //定义一个map，这个map不能直接赋值，没有分配空间
	idNames = make(map[int]string, 10) //第二个参数指定大小

	idNames[0] = "duke"
	idNames[1] = "liLy"

	for key, value := range idNames {
		fmt.Println("key: ", key, "value: ", value)
	}

	value, ok := idNames[10]
	if ok {
		fmt.Println("id=10 is existed,value: ", value)
	} else {
		fmt.Println("id=10 is not existed,value: ", value)
	}

	fmt.Println("before delete: ", idNames)
	//删除map中的key
	delete(idNames, 1)
	delete(idNames, 10) //删除不存在的不会报错
	fmt.Println("after delete: ", idNames)

	//并发任务执行的时候，需要对map上锁

	// sync map
	var syncMap sync.Map
	syncMap.Store("key1", "value1")

	// 获取键对应的值
	syncValue, ok := syncMap.Load("key1")
	if ok {
		fmt.Println(syncValue.(string))
	}

	// 遍历所有键值对
	syncMap.Range(func(key, value any) bool {
		fmt.Println(key.(string), value.(string))
		return true
	})

	syncMap.Delete("key1")
}

/*
output:

key:  1 value:  liLy
key:  0 value:  duke
id=1 is not existed,value:
before delete:  map[0:duke 1:liLy]
after delete:  map[0:duke]
value1
key1 value1
*/
